package com.hk.core.web.reactive.filters;

import com.hk.core.web.reactive.ServerWebExchangeUtils;
import org.springframework.core.Ordered;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;


/**
 * 解决body只能读取一次的问题
 *
 * @author Kevin
 * @date 2022-07-05 8:12
 */
public class RepeatBodyFilter implements WebFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        var request = exchange.getRequest();
        if (HttpMethod.POST.equals(request.getMethod())
                && MediaType.APPLICATION_JSON.isCompatibleWith(request.getHeaders().getContentType())) {
            return ServerWebExchangeUtils.cacheRequestBody(exchange, req ->
                    request == req ? chain.filter(exchange) :
                            chain.filter(exchange.mutate().request(req).build())
            );
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
